import datetime
import copy
from base import XMLBase, LinkType

class QueueLink(LinkType):
    _node_name = 'Queue'

class Queue(XMLBase):
    _node_name = 'Queue'
    _attrib_map = {'Name':'name',
                       'Description':'description',
                       'MaxNodes':'max_nodes',
                       'MaxTasksPerNode':'max_tasks_per_node'}

    def __init__(self, name=None, description=None,
                 wall_clock_limit=None, max_nodes=None,
                 max_tasks_per_node=None):

        self.name = name
        self.description = description
        # wall_clock_limit should be an instance of datetime.timedelta
        self.wall_clock_limit = wall_clock_limit
        self.max_nodes = max_nodes
        self.max_tasks_per_node = max_tasks_per_node

    def to_tuple(self):
        self._build_tuple()
        if self.wall_clock_limit:
            h = self.wall_clock_limit.days*24
            h += self.wall_clock_limit.seconds/3600
            m = (self.wall_clock_limit.seconds % 3600)/60
            s = self.wall_clock_limit.seconds % 60
            limit = '%02d:%02d:%02d' % (h, m, s)
            self._elements.append(('WallClockLimit', limit))
        return ('Queue', self._elements)

    def read(self, xml_str):
        XMLBase.read(self, xml_str)
        if self.max_nodes:
            self.max_nodes = int(self.max_nodes)
        if self.max_tasks_per_node:
            self.max_tasks_per_node = int(self.max_tasks_per_node)
        nodes = self._xmldoc.getElementsByTagName('WallClockLimit')
        if nodes:
            limit = nodes[0].childNodes[0].data
            limit = limit.split(':')
            h = int(limit[0])
            m = int(limit[1])
            s = int(limit[2])
            self.wall_clock_limit = datetime.timedelta(hours=h, 
                                                       minutes=m, seconds=s)

class ComputerLink(LinkType):
    _node_name = 'Computer'

class Computer(XMLBase):
    _node_name = 'Computer'
    _attrib_map = {'Name': 'name',
                   'Description': 'description',
                   'URL': 'url',
                   'OS': 'os',
                   'Arch': 'arch'}
    _list_map = {'Queue':{'attribute':'queues',
                              'class':Queue}}

    def __init__(self, name=None, description=None,
                 url=None, os=None, arch=None,
                 queues=[]):

        self.name = name
        self.description = description
        self.url = url
        self.os = os
        self.arch = arch
        self.queues = copy.copy(queues)
